package com.gitee.faster.webdav;

import cn.hutool.core.util.ServiceLoaderUtil;
import com.gitee.faster.webdav.common.HttpWebServer;
import com.gitee.faster.webdav.kernel.Configuration;
import com.gitee.faster.webdav.kernel.FasterWebDavServer;
import com.gitee.faster.webdav.kernel.event.EventListener;
import com.gitee.faster.webdav.kernel.event.EventPublisher;
import com.gitee.faster.webdav.kernel.event.NotificationEvent;
import com.gitee.faster.webdav.kernel.event.ShutdownEvent;
import com.gitee.faster.webdav.logger.LoggerLevel;
import com.gitee.faster.webdav.logger.ServiceProvider;
import lombok.Getter;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.Reporter;
import org.slf4j.spi.SLF4JServiceProvider;

import java.awt.*;

/**
 * @author hongda.li
 */
public final class FasterWebDavApplication implements EventListener<ShutdownEvent> {

    @Getter
    private static long timestamp;

    @Getter
    private static HttpWebServer webServer;

    static {
        loadLoggerProviderIfNotSlf4jImpl();
    }

    public static void main(String[] args) {
        // 初始化服务器
        webServer = new FasterWebDavServer();

        // 系统运行时间
        timestamp = System.currentTimeMillis();

        // 启动服务器
        webServer.start();
    }

    /**
     * 不存在其它实现 SLF4J 规范的日志框架时，加载日志模块
     */
    public static void loadLoggerProviderIfNotSlf4jImpl() {
        if (ServiceLoaderUtil.loadFirstAvailable(SLF4JServiceProvider.class) == null) {
            System.setProperty(Reporter.SLF4J_INTERNAL_VERBOSITY_KEY, LoggerLevel.WARN.name());
            System.setProperty(LoggerFactory.PROVIDER_PROPERTY_KEY, ServiceProvider.class.getName());
        }
    }

    @Override
    public void doListen(ShutdownEvent event) {
        // 关闭服务器
        webServer.shutdown();

        // 保存最新配置
        Configuration.getInstance().rewriteToJson();

        // 发送终止通知
        NotificationEvent notificationEvent = new NotificationEvent();
        notificationEvent.setMessage("WebDav服务关闭成功");
        notificationEvent.setMessageType(TrayIcon.MessageType.INFO);
        EventPublisher.getInstance().publishEvent(notificationEvent);

        // 退出虚拟机
        System.exit(0);
    }
}
